#import "NotificationManager.h"

@interface NotificationManager ()

@property NSMutableArray* notes;
@property NSMutableSet* receivedNotes;

@property NSTimer *updateTimer;
@property BOOL loadedOnce;
@end

static NSString *kNotificationsUrl = @"http://78.90.20.186:8080/ProjectRestaurant/getCurrentMessages";
static NSString* kMessageDoneUrl = @"http://78.90.20.186:8080/ProjectRestaurant/makeMessageDone";

@implementation NotificationManager

+ (id)sharedNotifications {
    static NotificationManager *sharedNotifications = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedNotifications = [[self alloc] init];
    });
    return sharedNotifications;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.notes = [[NSMutableArray alloc] init];
        self.receivedNotes = [[NSMutableSet alloc] init];
        self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
        [self update];
        
    }
    return self;
}

- (void) update{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:kNotificationsUrl]];
    NSURLSessionDataTask* downloadJSONTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
        NSError* mistake = nil;
        NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&mistake];
        
        NSArray* notes = jsonDictionary[@"response"];
        
        if (mistake != nil) {
            NSLog(@"Error : %@", [mistake localizedDescription]);
        }
        else {
            if (![jsonDictionary[@"response"] isEqual:@"No messages!"]) {
                for (NSDictionary *note in notes){
                    Notification *newNote = [[Notification alloc] init];
                    newNote.messageId = [note[@"messageId"] integerValue];
                    newNote.text = note[@"text"];
                    newNote.tableId = [note[@"tableId"] integerValue];
                    newNote.status = [note[@"status"] integerValue];
                    if ([self.receivedNotes containsObject:[NSNumber numberWithInteger:newNote.messageId]]) {
                        // Do nothing
                    }
                    else{
                        [self.notes addObject:newNote];
                        [self.receivedNotes addObject:[NSNumber numberWithInteger:newNote.messageId]];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:nil];
                        
                        if (self.loadedOnce) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"NewNotification" object:newNote userInfo:nil];
                        }
                    }
                }
                //if ([self.notes count] >= 0) {
                    self.loadedOnce = YES;
                //}
            }
        }
        
        
    }];
    [downloadJSONTask resume];
}

-(NSInteger) count{
    return [self.notes count];
}

-(Notification*) noteAtIndex:(NSInteger) index{
    if (index > -1 && index < [self count]) {
        return self.notes[index];
    }
    else{
        return nil;
    }
}



-(void)makeMessageDone:(Notification*)note{
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInteger:note.messageId] , @"messageId", nil];
    
    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        NSError *error = nil;
        NSData *result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error == nil && result != nil) {
            NSData *response = [self jsonPostRequest:result];
            
            NSError* mistake = nil;
            [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&mistake];
            
            if (mistake != nil) {
                NSLog(@"Error : %@", [mistake localizedDescription]);
            }
            else {
                [self.receivedNotes removeObject:[NSNumber numberWithInteger:note.messageId]];
                [self.notes removeObject:note];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:nil];
            }
        }
    }
}

-(id) jsonPostRequest:(NSData*) jsonRequestData{
    NSURL *url = [NSURL URLWithString:kMessageDoneUrl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];
    
    //send synch request
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    
    if (error == nil) {
        return result;
    }
    else{
        return nil;
    }
}

@end